import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/utils/api'
import type { User, UserCreate, UserLogin, UserUpdate, Token } from '@/types'

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string | null>(localStorage.getItem('token'))

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const isAdmin = computed(() => user.value?.is_admin || false)

  // 登录
  const login = async (loginData: UserLogin): Promise<void> => {
    try {
      // 使用JSON格式发送登录请求，包含邀请码
      const response = await api.post<Token>('/auth/login', loginData)
      
      const { access_token } = response.data
      
      if (access_token) {
        token.value = access_token
        localStorage.setItem('token', access_token)
      } else {
        throw new Error('登录失败：未收到访问令牌')
      }
      
      // 获取用户信息
      await fetchUserInfo()
    } catch (error) {
      throw error
    }
  }

  // 注册
  const register = async (userData: UserCreate): Promise<void> => {
    try {
      await api.post<User>('/auth/register', userData)
    } catch (error) {
      throw error
    }
  }

  // 获取用户信息
  const fetchUserInfo = async (): Promise<void> => {
    try {
      const response = await api.get<User>('/auth/me')
      user.value = response.data
    } catch (error) {
      // 如果获取用户信息失败，清除token
      logout()
      throw error
    }
  }

  // 更新用户信息
  const updateUser = async (userData: UserUpdate): Promise<void> => {
    try {
      const response = await api.put<User>('/users/me', userData)
      user.value = response.data
    } catch (error) {
      throw error
    }
  }

  // 登出
  const logout = (): void => {
    user.value = null
    token.value = null
    localStorage.removeItem('token')
  }

  // 初始化用户信息
  const initUser = async (): Promise<void> => {
    if (token.value) {
      try {
        await fetchUserInfo()
      } catch (error) {
        logout()
      }
    }
  }

  return {
    user,
    token,
    isLoggedIn,
    isAdmin,
    login,
    register,
    fetchUserInfo,
    updateUser,
    logout,
    initUser
  }
})
